#!/bin/sh

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

CRONTAB="/var/spool/cron/crontabs"
PIDFILE=/var/run/crond.pid
start() {
	if test -f $PIDFILE; then
		echo " PID File exists!"
		exit 1
	fi
	mkdir -p $CRONTAB
	for i in /etc/crond.d/*;do
		BN=`basename $i`
		echo "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/opendomo"> /var/spool/cron/crontabs/$BN
		grep -h -v '#' $i/* >> /var/spool/cron/crontabs/$BN
	done
       
	#TODO Tal vez cron deba registrar eventos en el syslog? (-S)
	# Nota: si se activa -S se registran todos los eventos como cron.err!!
	touch /var/log/crond.log
	chown admin:admin /var/log/crond.log 2>/dev/null
	/usr/sbin/crond -L /var/log/crond.log -l 6 > /dev/null 
	if test "$?" -eq "0"; then
		PID=`ps -ef | grep "/usr/sbin/crond" | grep -v grep | cut -b1-5`
		echo $PID > $PIDFILE
		/usr/bin/logger -p notice "Service crond started"
		exit 0
	else
		/usr/bin/logger -p error "Service crond NOT started"
		exit 1
	fi

}
stop(){
        PID=`cat $PIDFILE`
        kill -9 $PID
        rm $PIDFILE

}
restart() {
	stop
	start 
}
case "$1" in
  start)
  	echo -n "Starting CRON "
  	start
	;;
  stop)
  	echo -n "Stopping CRON "
  	stop
	;;
  restart|reload)
	echo -n "Restarting CRON "
  	restart
	;;
  *)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
esac

